<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    require_once realpath( dirname( __FILE__ ) . '/../..' ) . "/Classes.php" ;

    /**
     * This class change the php autoload method to customize with all the project classes
     *
     * @package    kassiop
     * @subpackage core
     *
     * @author NairuS
     * @version 1.3 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     *
     */
    class Autoload
    {
        public function __construct()
        {
            $this->baseDir = realpath( dirname( __FILE__ ) . '/../..' ) . '/' ;
        }

        /**
         * Defines the root the classes pakage.
         * @var string
         */
        protected $baseDir = '' ;

        /**
         * Defines all the classes to load.
         *
         * @desc Do not modify here, it is used with make buildClasses method.
         * see Classes.php file
         *
         * @var array
         */
        protected $classes = array();

        /**
         * Defines the file or folder to exlude on buildClasses method.
         *
         * @var array
         */
        protected static $excludedFiles = array
        (
            '.',
            '..',
            '.svn',
            'bootstrap.php',
            'buildAutoloadClasses.php',
            'config',
            'modules',
            'templates'
        ) ;

        /**
         * Defines if the autoload classes has been regristered
         * @var boolean
         */
        protected static $registered = false ;

        /**
         * Defines the singleton of the Autoload class.
         * @var Autoload
         */
        protected static $instance = null ;

        /**
         * Handles autoloading of classes.
         *
         * @param string $class A class name.
         *
         * @return boolean Returns true if the class has been loaded
         */
        public function autoloadClass( $class )
        {
            if( !Classes::contains( $class ) )
            {
                return false ;
            }

            require $this->baseDir . Classes::get( $class ) . '/' . $class . '.php' ;

            return true;
        }

        /**
         * Returns the base directory this autoloader is working on.
         *
         * @return base directory
         */
        public function getBaseDir()
        {
            return $this->baseDir ;
        }

        /**
         * Makes the autoload package.
         *
         * <code>
         *     //Create a file named buildAutoloadClasses.php on the root package and write the lines bellow.
         *     require dirname( __FILE__ ) . "/com/dozrok/autoload/Autoload.php" ;
         *     $autoload = Autoload::getInstance() ;
         *     $autoload->make();
         *
         *     //Launch the script:
         *     php /path/to/libs/buildAutoloadClasses.php
         * </code>
         *
         * @return void
         */
        public function make()
        {
            // tries to open the base directory to make the package.
            $handle = @opendir( $this->baseDir ) or die( "Unable to open $this->baseDir" ) ;

            // unsets all the classes.
            $this->classes = array() ;

            // builds all the classes package.
            $this->buildClasses( $handle, $this->baseDir ) ;

            // writes the new package in Autoload class.
            $content = preg_replace( '/private static \$classes = array *\(.*?\)/s', 'private static $classes = ' . var_export( $this->classes, true ), file_get_contents( $this->baseDir . "/Classes.php" ) ) ;
            file_put_contents( $this->baseDir . "/Classes.php", $content);
        }

        /**
         * Retrieves the singleton of this class
         *
         * @return Autoload A Autoload singleton.
         */
        public static function getInstance()
        {
            if( !isset( self::$instance ) )
            {
                self::$instance = new Autoload() ;
            }
            return self::$instance ;
        }

        /**
         * Register Autoload in spl autoloader.
         *
         * @return void
         */
        public static function register()
        {
            if( self::$registered )
            {
                return ;
            }

            ini_set( 'unserialize_callback_func' , 'spl_autoload_call' ) ;
            if( spl_autoload_register( array( self::getInstance(), 'autoloadClass' ) ) === false )
            {
                throw new Exception( sprintf( 'Unable to register %s::autoload as an autoloading method.' , get_class( self::getInstance() ) ) ) ;
            }
            self::$registered = true ;
        }

        /**
         * Unregister Autoload from spl autoloader.
         *
         * @return void
        */
        public static function unregister()
        {
            spl_autoload_unregister( array( self::getInstance() , 'autoloadClass' ) ) ;
            self::$registered = false;
        }

        /**
         * Browses all the package and build the $classes property.
         *
         * @param directory $handle The directory instance to read.
         * @param string $path      The path to browse.
         * @return void
         */
        protected function buildClasses( $handle, $path )
        {
            //running the while loop
            while( false !== ( $file = readdir( $handle ) ) )
            {
                $dir = $path.'/'.$file;
                if( is_dir( $dir ) && !in_array( $file , array_merge( self::$excludedFiles, Classes::$excludedFiles ) ) )
                {
                    $handle2 = @opendir( $dir ) or die( "undable to open file $file" );
                    $this->buildClasses( $handle2, $dir ) ;
                }
                elseif( !in_array( $file , array_merge( self::$excludedFiles, Classes::$excludedFiles ) ) && pathinfo( $file, PATHINFO_EXTENSION ) === 'php' )
                {
                    $classPath = str_replace( array( $this->baseDir , $file ) , array( '' , '' ) , $dir ) ;
                    $this->classes[basename( $file , '.php' )] = $classPath ;
                }
            }

            //closing the directory
            closedir($handle);
        }
    }
?>